package com.masterclient.app.modules.order.contract;

import com.eoner.baselib.container.CommonBaseResponse;
import com.eoner.baselib.presenter.ThrowableConsumer;
import com.eoner.baselib.utils.toast.ToastUtil;
import com.eoner.baselibrary.bean.order.OrderSendDeliveryBean;
import com.eoner.baselibrary.bean.order.PayInfoBean;
import com.eoner.baselibrary.bean.order.PresentationShareBean;
import com.eoner.common.bean.base.CommonBaseBean;
import com.masterclient.app.httpservice.RetrofitUtil;
import com.masterclient.app.httpservice.RetrofitUtil2;
import com.eoner.baselibrary.bean.order.OrderListBean;
import com.eoner.baselibrary.bean.order.PaymentBean;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import okhttp3.RequestBody;

/**
* Created by TMVPHelper on 2017/07/27
*/
public class OrderListPresenter extends OrderListContract.Presenter{


    @Override
    public void aliPrepay(String trade_no,String payment_id) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("trade_no",trade_no);
            jsonObject.put("payment_id",payment_id);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),
                jsonObject.toString());
        Observable<PayInfoBean> observable = RetrofitUtil2.getInstance().aliPrePay(body);

        Disposable disposable = toSubscribe(observable, (Consumer<PayInfoBean>) bean -> {
            if(bean!=null && "0".equals(bean.getCode())){
                mView.setAliPrePayInfo(bean.data);
            }else {
                mView.showFail(bean.getMsg());
            }
        },new ThrowableConsumer());
        mRxManager.add(disposable);
    }

    @Override
    public void modifyAddress(String trade_id, String order_id, String address_id) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("trade_id",trade_id);
            jsonObject.put("order_id",order_id);
            jsonObject.put("address_id",address_id);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),
                jsonObject.toString());
        Observable<CommonBaseBean> observable;
        observable = RetrofitUtil2.getInstance().modifyAddress(body);

        Disposable disposable = toSubscribe(observable, (Consumer<CommonBaseBean>) bean -> {
            if (bean != null && "0".equals(bean.getCode())) {
                mView.modifyAddressSuccess(bean.getMsg());
            } else {
                mView.modifyAddressFail(bean.getMsg());
            }
        }, new ThrowableConsumer() {
            @Override
            public void accept(Throwable o) throws Exception {
                super.accept(o);
                mView.modifyAddressFail("网络异常，请重试");
            }
        });
        mRxManager.add(disposable);
    }

    @Override
    public void saleOrdersList(String is_auto, String status, String type,
                              String is_screen , String page, String page_size) {
        toSubscribe("1".equals(is_auto)?RetrofitUtil2.getInstance().saleOrdersAutoList(status,type,is_screen,page,page_size):
                        RetrofitUtil2.getInstance().saleOrdersList(status,type,is_screen,page,page_size),
                new Consumer<OrderListBean> () {
                    @Override
                    public void accept(@NonNull OrderListBean bean) throws Exception {
                        if("0".equals(bean.getCode())){
                            mView.showOrderList(bean.getData());
                        }else {
                            mView.loadNull();
                            mView.loadFailed();
                        }
                    }
                },new ThrowableConsumer(){
                    @Override
                    public void accept(Throwable o) throws Exception {
                        super.accept(o);
                        mView.loadFailed();
                    }
                });
    }

    @Override
    public void purchaseOrderList(String page, String page_size, String status) {
        toSubscribe(RetrofitUtil2.getInstance().purchaseOrderList(status,page,page_size),
                new Consumer<OrderListBean> () {
                    @Override
                    public void accept(@NonNull OrderListBean bean) throws Exception {
                        if("0".equals(bean.getCode())){
                            mView.showOrderList(bean.getData());
                        }else {
                            mView.loadNull();
                            mView.loadFailed();
                        }
                    }
                },new ThrowableConsumer(){
                    @Override
                    public void accept(Throwable o) throws Exception {
                        super.accept(o);
                        mView.loadFailed();
                    }
                });
    }

    @Override
    public void getOrderList(String type,String page, String page_size,String keyword) {
        Observable<OrderListBean> observable;
        if (type.equals("order_search")){
            observable = RetrofitUtil.getInstance().searchOrderList(keyword,page,page_size);
        }else {
            observable = RetrofitUtil.getInstance().getOrderList(type, page, page_size);
        }

        Disposable disposable = toSubscribe(observable, new Consumer<OrderListBean> () {
            @Override
            public void accept(@NonNull OrderListBean bean) throws Exception {
                if("0".equals(bean.getCode())){
                    mView.showOrderList(bean.getData());
                }else {
                    mView.loadNull();
                    mView.loadFailed();
                }
            }
        },new ThrowableConsumer(){
            @Override
            public void accept(Throwable o) throws Exception {
                super.accept(o);
                mView.loadFailed();
            }
        });
        if(mRxManager != null){
            mRxManager.add(disposable);
        }else{
            mView.loadFailed();
        }
    }

    @Override
    public void recieverOrder(String id) {
        Observable<CommonBaseBean> observable = RetrofitUtil.getInstance().recieverOrder(id);
        Disposable disposable = toSubscribe(observable, new Consumer<CommonBaseBean>() {
            @Override
            public void accept(@NonNull CommonBaseBean bean) throws Exception {
                if("0".equals(bean.getCode())){
                    mView.operateSuccess(-1,"收货成功");
                }else {
                    mView.showFail(bean.getMsg());
                }
            }
        },new ThrowableConsumer());
        mRxManager.add(disposable);
    }

    @Override
    public void removeOrder(String id) {
        Observable<CommonBaseBean> observable = RetrofitUtil.getInstance().removeOrder(id);
        Disposable disposable = toSubscribe(observable, new Consumer<CommonBaseBean>() {
            @Override
            public void accept(@NonNull CommonBaseBean bean) throws Exception {
                if("0".equals(bean.getCode())){
                    mView.operateSuccess(-1,"删除订单成功");
                }else {
                    mView.showFail(bean.getMsg());
                }
            }
        },new ThrowableConsumer());
        mRxManager.add(disposable);
    }

    @Override
    public void cancleOrder(String reason, String id) {
        Observable<CommonBaseBean> observable = RetrofitUtil.getInstance().cancleOrder(reason,id);
        Disposable disposable = toSubscribe(observable, new Consumer<CommonBaseBean>() {
            @Override
            public void accept(@NonNull CommonBaseBean bean) throws Exception {
                if("0".equals(bean.getCode())){
                    mView.operateSuccess(-1,"取消订单成功");
                }else {
                    mView.showFail(bean.getMsg());
                }
            }
        },new ThrowableConsumer());
        mRxManager.add(disposable);
    }

    @Override
    public void payNow(String trade_no) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("trade_no",trade_no);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),
                jsonObject.toString());
        Observable<PaymentBean> observable = RetrofitUtil2.getInstance().validPayment(body);
        Disposable disposable = toSubscribe(observable, new Consumer<PaymentBean>() {
            @Override
            public void accept(@NonNull PaymentBean bean) throws Exception {
                if("0".equals(bean.getCode())){
                    mView.getPaymentSuccess(bean.getData());
                }else {
                    mView.showFail(bean.getMsg());
                }
            }
        },new ThrowableConsumer());
        mRxManager.add(disposable);
    }

    @Override
    public void getShareData(String order_no) {
        Observable<PresentationShareBean> observable = RetrofitUtil2.getInstance().getPresentationShare(order_no);
        Disposable disposable = toSubscribe(observable, (Consumer<PresentationShareBean>) bean -> {
            if (bean != null && bean.getData() != null) {
                mView.getShareDataSuccess(bean);
            } else {
                ToastUtil.showToast("分享失败");
            }
        }, new ThrowableConsumer() {
            @Override
            public void accept(Throwable o) throws Exception {
                super.accept(o);
                ToastUtil.showToast("请检查网络");
            }
        });
        mRxManager.add(disposable);
    }

    public void upReserve(int position,String order_id) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("id",order_id);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),
                jsonObject.toString());
        mRxManager.add(toSubscribe(RetrofitUtil2.getInstance().upReserve(body), new Consumer<CommonBaseResponse>() {
            @Override
            public void accept(@NonNull CommonBaseResponse bean) throws Exception {
                if(bean.getCode() == 0){
                    mView.operateSuccess(position,"让上级代发成功");
                }else {
                    mView.showFail(bean.getMsg());
                }
            }
        }, new ThrowableConsumer(){
            @Override
            public void accept(Throwable o) throws Exception {
                super.accept(o);
                mView.showFail("网络异常，请重试");
            }
        }));
    }

    @Override //pick_up 提货，delivery_good 拨货,check_send 自己发货
    public void checkGoods(int position,String order_id, String type) {
        mRxManager.add(toSubscribe("pick_up".equals(type)?RetrofitUtil2.getInstance().pickUpGoods(order_id):"delivery_good".equals(type)?
                        RetrofitUtil2.getInstance().checkDeliveryGoods(order_id):RetrofitUtil2.getInstance().checkSend(order_id),
                new Consumer<CommonBaseResponse<Map<String,String>>>() {
            @Override
            public void accept(@NonNull CommonBaseResponse<Map<String,String>> bean) throws Exception {
                if(bean.getCode() == 0){
                    Map<String, String> map = bean.getData();
                    map.put("relation_order_id",order_id);
                    map.put("type",type);
                    map.put("position",String.valueOf(position));
                    mView.checkGoodsSuccess(map);
                }else {
                    mView.showFail(bean.getMsg());
                }
            }
        }, new ThrowableConsumer(){
            @Override
            public void accept(Throwable o) throws Exception {
                super.accept(o);
                mView.showFail("网络异常，请重试");
            }
        }));
    }

    @Override
    public void sendDelivery(int position, String order_id) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("order_id",order_id);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),
                jsonObject.toString());
        mRxManager.add(toSubscribe(RetrofitUtil2.getInstance().toSendDelivery(body), new Consumer<CommonBaseResponse<OrderSendDeliveryBean>>() {
            @Override
            public void accept(@NonNull CommonBaseResponse<OrderSendDeliveryBean> bean) throws Exception {
                if(bean.getCode() == 0){
                    mView.sendDeliverySuccess(position,bean.getData());
                }else {
                    mView.showFail(bean.getMsg());
                }
            }
        }, new ThrowableConsumer(){
            @Override
            public void accept(Throwable o) throws Exception {
                super.accept(o);
                mView.showFail("网络异常，请重试");
            }
        }));
    }
}